<template>
    <el-card>
        <el-form :inline="true" class="form">
            <el-form-item label="用户名：">
                <el-input placeholder="请你输入搜索职位关键词" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="keyword ? false : true" @click="search">搜索</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0px;">
        <el-button type="primary" icon="Plus" @click="addRole">添加职位</el-button>
        <el-table border style="margin: 10px 0px;" :data="roleArr">
            <el-table-column label="#" type="index" align="center"></el-table-column>
            <el-table-column label="ID" align="center" prop="id"></el-table-column>
            <el-table-column label="角色名称" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="270px" align="center">
                <template #="{ row, $index }">
                    <el-button type="primary" size="small" icon="User" @click="setPermisstion(row)">分配权限</el-button>
                    <el-button type="warning" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
                    <el-popconfirm :title="`确定删除${row.roleName}?`" width="260px" @confirm="removeRole(row.id)">
                        <template #reference>
                            <el-button type="danger" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
            layout="prev, pager, next, jumper,->,sizes,total" :total="total" @current-change="getHasRole"
            @size-change="getHasRole" />
    </el-card>
    <!-- 添加职位与更新职位的结构：对话框 -->
    <el-dialog v-model="dialogVisite" :title="RoleParams.id ? '更新职位' : '添加职位'">
        <el-form :model="RoleParams" :rules="rules" ref="form">
            <el-form-item label="职位名称" prop="roleName">
                <el-input placeholder="请输入职位名称" v-model="RoleParams.roleName"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="dialogVisite = false">取消</el-button>
            <el-button type="primary" @click="save"> 确定</el-button>
        </template>
    </el-dialog>
    <!-- 抽屉组件：分配职位的菜单权限与按钮的权限 -->
    <el-drawer v-model='drawer'>
        <!-- 头部标题：将来文字应该动态 -->
        <template #header>
            <h4>分配菜单与按钮的权限 </h4>
        </template>
        <!-- 身体部分 -->
        <template #default>
            <!-- 树型控件 -->
            <el-tree ref='tree':data="menuArr" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="selectArr" :props="defaultProps">
            </el-tree>
        </template>
        <template #footer>
            <el-button @click="drawer = false">取消</el-button>
            <el-button type="primary" @click="handler"> 确定</el-button>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import useLayOutSettingStore from '@/store/modules/setting';
import { ref, onMounted, reactive, nextTick } from 'vue';
import { RoleResponseData, Records, Role ,MenuResponseData,MenuList} from '@/api/acl/role/type';
import { reqRoleInfo, reqAddOrUpdateRole ,reqAllMenuList,reqSetPermisstion,reqRemoveRole} from '@/api/acl/role/index';
//当前页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(10);
let keyword = ref<string>('');
let total = ref<number>(0);
let roleArr = ref<Records>([]);
//控制对话框的显示与隐藏
let dialogVisite = ref<boolean>(false);
//获取模板setting仓库
let settingStore = useLayOutSettingStore();
//获取form组件实例
let form = ref<any>();
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false);
//定义数组存储用户权限的数据
let menuArr=ref<MenuList>([]);
//收集新增岗位数据
//准备一个数组 ：用于存储勾选的节点的ID（四级的）
let selectArr=ref<number[]>([]);
let RoleParams = reactive<Role>({
    roleName: ''
});
//获取tree组件实例
let tree=ref<any>();
onMounted(() => {
    getHasRole();
})
//获取全部已有的角色信息
const getHasRole = async (pager = 1) => {
    //收集当前页码
    pageNo.value = pager;
    let result: RoleResponseData = await reqRoleInfo(pageNo.value, pageSize.value, keyword.value)
    if (result.code == 200) {
        total.value = result.data.total;
        roleArr.value = result.data.records;
    }
}
//搜索按钮的回调
const search = () => {
    //再次发请求根据关键字
    getHasRole();
    keyword.value = '';
}
//重置按钮的回调
const reset = () => {
    settingStore.refresh = !settingStore.refresh;
}
//添加职位按钮回调
const addRole = () => {
    // 对话框显示
    dialogVisite.value = true;
    //清空数组
    Object.assign(RoleParams, {
        roleName: '',
        id: 0
    });
    //清空上一次表单校验的错误结果
    nextTick(() => {
        form.value.clearValidate("roleName");
    })
}
//更新已有的职位按钮的回调
const updateRole = (row: Role) => {
    // 对话框显示
    dialogVisite.value = true;
    //存储已有的职位----带有id的
    Object.assign(RoleParams, row);
    //清空上一次表单校验的错误结果
    nextTick(() => {
        form.value.clearValidate("roleName");
    })
}
//自定义校验规则的回调
const validatorRoleName = (rules: any, value: any, callBack: any) => {
    if (value.trim().length >= 2) {
        callBack();
    } else {
        callBack(new Error('职位名称至少两位'))
    }
}
//职位相关的校验规则
const rules = {
    roleName: [
        { required: true, trigger: 'blur', validator: validatorRoleName }
    ]
}
//确定按钮的回调
const save = async () => {
    //表单校验结果，结果通过再发请求，结果不通过不应该发请求
    await form.value.validate();
    //添加职位|更新职位请求
    let result: any = await reqAddOrUpdateRole(RoleParams);
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: RoleParams.id ? '更新成功' : '添加成功'
        });
        //对话框消失
        dialogVisite.value = false;
        //再次获取全部已有的职位
        getHasRole(RoleParams.id ? pageNo.value : 1);//更新有id留在当前页，新增没id回到第一页
    }
}
//分配权限按钮的回调;row已有的职位数据
const setPermisstion = async(row:Role) => {
    //抽屉显示
    drawer.value = true
    //收集当前要分类权限的职位的数据
    Object.assign(RoleParams,row);
    //根据职位获取权限的数据
    let result:MenuResponseData=await reqAllMenuList((RoleParams.id as number));
    if(result.code==200){
        menuArr.value=result.data;
        selectArr.value=filterSelectArr(menuArr.value,[]);
    }
}
const filterSelectArr=(allData:any,initArr:any)=>{
    allData.forEach((item:any)=>{
        if (item.select&&item.level==4){
            initArr.push(item.id)
        }//递归
        if (item.children&&item.children.length>0){
            filterSelectArr(item.children,initArr)
        }
    })
}
//树型控件测试数据
const defaultProps={
    children:'children',
    label:'name'
}
//抽屉确定按钮的回调
const handler=async()=>{
    //职位ID
    const roleId=(RoleParams.id as number);
    //选中节点的id
    let arr=tree.value.getCheckedKeys();
    //半选的id
    let arr1 = tree.value.getHalfCheckedKeys();
    let permissionId = arr.concat(arr1);
    //下发权限
    let result: any = await reqSetPermisstion(roleId, permissionId);
    if (result.code == 200) {
        //抽屉关闭
        drawer.value = false;
        //提示信息
        ElMessage({ type: 'success', message: '分配权限成功' });
        //页面刷新
        window.location.reload();
    }
}
//删除已有的职位
const removeRole=async(id:number)=>{
    let result:any=await reqRemoveRole(id);
    if(result.code==200){
        ElMessage({ type: 'success', message: '删除成功' });
        //再次获取全部已有的职位
        getHasRole(roleArr.value.length>1?pageNo.value:pageNo.value-1);
    }
}
</script>

<style lang="scss" scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
}
</style>
